package com.fzy.core.system.action;

import ge.core.system.entity.Entity;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import com.fzy.core.system.service.DbService;
import com.fzy.core.utils.U;
import com.fzy.core.webwork.BaseAction;
import com.fzy.core.webwork.MyValidationAware;
import com.opensymphony.xwork.ModelDriven;
import com.opensymphony.xwork.Preparable;

public class EntityInputAction extends BaseAction implements
		MyValidationAware, Preparable, ModelDriven {

	private static final long serialVersionUID = -6545776513894162109L;
	String errorDispatch;
	Entity entity;
	DbService dbService;
	boolean isEntityFound;
	List properties;

	public void prepare() throws Exception {
		errorDispatch = "dispatcher:/pages/refresh-parent.jsp";
		entity = (Entity) validateIdAndGetEntity(request.getParameter("id"),
				Entity.class);

		// only for delete operation
		isEntityFound = entity != null;

		// default values
		if (entity == null) {
			entity = new Entity();
			entity.setPackageText("ge.app");
        	entity.setHasPrefix("1");
    		entity.setPrefixText("ru");
    		entity.setIsWork("1");
    		entity.setIsParentMapping("1");
		}
	}

	public String execute() throws Exception {
		if(entity.getId() == null){
			properties = new LinkedList();
		}else{
			properties = dbService.getPropertiesByEntityId(entity.getId());
		}
		return "dispatcher:/WEB-INF/jsp/core/system/entity-input.jsp";
	}

	public String delete() throws Exception {
		if (isEntityFound) {
			entity.setStatus("0");
			entity.setUpdatedDate(new Date());
			entity.setUpdatedUser(U.getUser());
			dbService.update(entity);

			addActionMessage(getText("success.save"));
		} else {
			addActionError(getText("error.entityMissing",
					new String[] { request.getParameter("id") }));
		}
		return "dispatcher:/pages/refresh-parent.jsp";
	}

	public String getErrorDispatch() {
		return errorDispatch;
	}

	public void setDbService(DbService dbService) {
		this.dbService = dbService;
	}

	public Object getModel() {
		return entity;
	}

	public List getProperties() {
		return properties;
	}

}
